package org.nobody.mallb2c.mallproduct.service.impl;

import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.nobody.common.constant.ProductConstant;
import org.nobody.common.to.SkuHasStockVo;
import org.nobody.common.to.SkuReductionTo;
import org.nobody.common.to.SpuBoundTo;
import org.nobody.common.to.es.SkuEsModel;
import org.nobody.common.utils.R;
import org.nobody.mallb2c.mallproduct.entity.*;
import org.nobody.mallb2c.mallproduct.feign.CouponFeignService;
import org.nobody.mallb2c.mallproduct.feign.SearchFeignService;
import org.nobody.mallb2c.mallproduct.feign.WareFeignService;
import org.nobody.mallb2c.mallproduct.service.*;
import org.nobody.mallb2c.mallproduct.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nobody.common.utils.PageUtils;
import org.nobody.common.utils.Query;

import org.nobody.mallb2c.mallproduct.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

  @Autowired
  SpuInfoDescService spuInfoDescService;

  @Autowired
  SpuImagesService spuImagesService;

  @Autowired
  AttrService attrService;

  @Autowired
  ProductAttrValueService productAttrValueService;

  @Autowired
  SkuInfoService skuInfoService;

  @Autowired
  SkuImagesService skuImagesService;

  @Autowired
  SkuSaleAttrValueService skuSaleAttrValueService;

  @Autowired
  CouponFeignService couponFeignService;

  @Autowired
  BrandService brandService;

  @Autowired
  CategoryService categoryService;

  @Autowired
  WareFeignService wareFeignService;

  @Autowired
  SearchFeignService searchFeignService;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<SpuInfoEntity> page = this.page(
      new Query<SpuInfoEntity>().getPage(params),
      new QueryWrapper<SpuInfoEntity>()
    );

    return new PageUtils(page);
  }

  @Transactional
  @Override
  public void saveSpuInfo(SpuSaveVo spuInfo) {
    //1、 保存spu基本信息 pms_spu_info
    SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
    BeanUtils.copyProperties(spuInfo, spuInfoEntity);
    spuInfoEntity.setCreateTime(new Date());
    spuInfoEntity.setUpdateTime(new Date());
    this.saveBaseSpuInfo(spuInfoEntity);

    //2、 保存spu的描述图片 pms_spu_info_desc
    List<String> decript = spuInfo.getDecript();
    SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
    descEntity.setSpuId(spuInfoEntity.getId()/*←上一步调用save方法后,spuId会自动保存到spuInfoEntity中*/);
    descEntity.setDecript(String.join(",", decript));
    spuInfoDescService.saveSpuInfoDesc(descEntity);

    //3、 保存spu的图片集 pms_spu_images
    List<String> images = spuInfo.getImages();
    if (!CollectionUtils.isEmpty(images)) {
      spuImagesService.saveImages(spuInfoEntity.getId(), images);
    }

    //4、 保存spu的规格参数 pms_product_attr_value
    //这里冗余了一个字段 attr_name
    List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
    if (!CollectionUtils.isEmpty(baseAttrs)) {
      List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
        ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
        valueEntity.setAttrId(attr.getAttrId());
        AttrEntity id = attrService.getById(attr.getAttrId());
        valueEntity.setAttrName(id.getAttrName());
        valueEntity.setAttrValue(attr.getAttrValues());
        valueEntity.setQuickShow(attr.getShowDesc());
        valueEntity.setSpuId(spuInfoEntity.getId());

        return valueEntity;
      }).collect(Collectors.toList());
      productAttrValueService.saveProductAttr(collect);
    }

    //5、 保存spu的积分信息 sms_spu_bounds
    Bounds bounds = spuInfo.getBounds();
    SpuBoundTo spuBoundTo = new SpuBoundTo();
    BeanUtils.copyProperties(bounds, spuBoundTo);
    spuBoundTo.setSpuId(spuInfoEntity.getId());
    R r = couponFeignService.saveSpuBounds(spuBoundTo);
    if (r.getCode() != 0) {
      log.error("远程保存spu积分信息失败");
    }

    //6、 保存当前spu对应的所有sku信息
    List<Skus> skus = spuInfo.getSkus();
    if (skus != null && skus.size() > 0) {
      skus.forEach(item -> {
        //6.1) sku的基本信息pms_sku_info
        //↓为了在pms_sku_info表中冗余一个 sku_default_img字段
        String defaultImg = "";
        for (Images image : item.getImages()) {
          if (image.getDefaultImg() == 1) {
            defaultImg = image.getImgUrl();
          }
        }
        SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
        BeanUtils.copyProperties(item, skuInfoEntity);
        skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
        skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
        skuInfoEntity.setSaleCount(0L);
        skuInfoEntity.setSpuId(spuInfoEntity.getId());
        skuInfoEntity.setSkuDefaultImg(defaultImg);//←这里冗余了 sku_default_img
        skuInfoService.saveSkuInfo(skuInfoEntity);

        Long skuId = skuInfoEntity.getSkuId();

        //6.2) sku的图片信息pms_sku_info
        List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
          SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
          skuImagesEntity.setSkuId(skuId);
          skuImagesEntity.setImgUrl(img.getImgUrl());
          skuImagesEntity.setDefaultImg(img.getDefaultImg());
          return skuImagesEntity;
        }).filter(entity -> {
          //返回false会被剔除
          return !StringUtils.isEmpty(entity.getImgUrl()); //没有图片（商品详情） 路径无需保存
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(imagesEntities)) skuImagesService.saveBatch(imagesEntities);

        //6.3) sku的销售属性信息pms_sku_sale_attr_value
        List<Attr> attr = item.getAttr();
        List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
          SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
          BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
          skuSaleAttrValueEntity.setSkuId(skuId);
          return skuSaleAttrValueEntity;
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(skuSaleAttrValueEntities))
          skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

        //6.4) sku的优惠、满减等信息pms_sku_lader(满几件打几折)、pms_sku_full-reduction(满多少减多少)、sms_member_price
        SkuReductionTo skuReductionTo = new SkuReductionTo();
        BeanUtils.copyProperties(item, skuReductionTo);
        skuReductionTo.setSkuId(skuId);
        //这里的skuReductionTo里包括了 满几件打几折 和 满多少减多少 两种情况
        if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1/*← 即>0时*/) {
          R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
          if (r1.getCode() != 0) {
            log.error("远程保存spu优惠信息失败");
          }
        }
      });
    }
  }

  @Override
  public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
    this.baseMapper.insert(spuInfoEntity);
  }

  @Override
  public PageUtils queryPageByCondition(Map<String, Object> params) {
    QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
    //(id=a or spu_name like %a%) and status = 1 and brand_id = 2 and catalogId = 3
    String key = (String) params.get("key");
    if (!StringUtils.isEmpty(key)) {
      wrapper.and((w) -> {
        w.eq("id", key).or().like("spu_name", key);
      });
    }
    //
    String status = (String) params.get("status");
    if (!StringUtils.isEmpty(status)) {
      wrapper.eq("publish_status", status);
    }

    String brandId = (String) params.get("brandId");
    if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
      wrapper.eq("brand_id", brandId);
    }

    String catalogId = (String) params.get("catalogId");
    if (!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
      wrapper.eq("catalog_id", catalogId);
    }


    IPage<SpuInfoEntity> page = this.page(
      new Query<SpuInfoEntity>().getPage(params),
      wrapper
    );

    return new PageUtils(page);
  }

  @Override
  public void up(Long spuId) {
    //组装需要的数据
    //1、 查出当前spuid对应的所有sku信息
    List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);


    //2、 重新封装每个sku的信息(准备存入es)

    //查询当前sku的所有可以用来被检索的规格属性
    List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistforspu(spuId); //调出该spu拥有的所有规格参数(之所以这里不能一次性调出可搜索的规格参数,是因为pms_product_attr_value表中没有冗余这个字段,只有pms_attr中有)
    List<Long> attrIds = baseAttrs.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList()); //这些规格参数对应的attr_id组成的集合
    List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds); //根据pms_attr 挑出search_type为1的
    Set<Long> idSet = new HashSet<>(searchAttrIds);
    List<SkuEsModel.Attr> attrList = baseAttrs.stream()
      .filter(item -> idSet.contains(item.getAttrId()))
      .map(item -> {
        SkuEsModel.Attr attr = new SkuEsModel.Attr();
        BeanUtils.copyProperties(item, attr);
        return attr;
      }).collect(Collectors.toList());

    //
    List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
    Map<Long, Boolean> stockMap = null;
    try {
      R r = wareFeignService.getSkusHasStock(skuIdList);
      TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
      };
      stockMap = r.getData(typeReference).stream().collect(/*收集成map→*/Collectors.toMap(SkuHasStockVo::getSkuId/*←什么当做key*/, item -> item.getHasStock()/*←什么当做value*/));
    } catch (Exception e) {
      log.error("库存服务查询异常:原因{}", e);
    }

    Map<Long, Boolean> finalStockMap = stockMap;
    List<SkuEsModel> upProducts = skus.stream().map(sku -> {
      SkuEsModel esModel = new SkuEsModel();
      BeanUtils.copyProperties(sku, esModel);
      esModel.setSkuPrice(sku.getPrice());
      esModel.setSkuImg(sku.getSkuDefaultImg());

      //设置库存信息
      if (finalStockMap == null) { //说明之前获取库存发生异常了,我们这里姑且认为库存是有的
        esModel.setHasStock(true);
      } else {
        esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
      }

      //todo 热度评分
      esModel.setHotScore(0L);

      //品牌和分类的名字
      BrandEntity brand = brandService.getById(esModel.getBrandId());
      esModel.setBrandName(brand.getName());
      esModel.setBrandImg(brand.getLogo());
      CategoryEntity category = categoryService.getById(esModel.getCatalogId());
      esModel.setCatalogName(category.getName());

      //设置检索属性
      esModel.setAttrs(attrList);

      return esModel;
    }).collect(Collectors.toList());

    //todo 发送给es(mall-search)进行保存
    R r = searchFeignService.productStatusUp(upProducts);
    if (r.getCode() == 0) {
      //远程调用成功
      //修改spu的状态
      baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
    } else {
      //远程调用失败
      //todo 重试 (接口幂等性)

      //Feign调用流程:
      /*
        1、构造请求数据,将对象转为json
          RequestTemplate template = buildTemplateFromArgs.create(argv)
        2、发送请求进行执行(执行成功后会解码响应数据)
          executeAndDecode(template)
        3、执行请求会有重试机制
          while(true){
            try{
              executeAndDecode(template);
            }catch(){
              try{
                retryer.continueOrPropagate(e)
              }catch(){
                throw ex;
              }
              continue;
            }
          }
      * */
    }
  }

  @Override
  public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
    SkuInfoEntity byId = skuInfoService.getById(skuId);
    Long spuId = byId.getSpuId();
    SpuInfoEntity spuInfoEntity = getById(spuId);
    return spuInfoEntity;
  }

}
